import re
from urllib import request
# 读取HTML代码


url = 'file:///D:/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/python/%E7%88%AC%E8%99%AB/untitled/%E5%89%AF%E6%95%99%E6%8E%88-%E6%95%B0%E5%AD%97%E5%AA%92%E4%BD%93%E4%B8%8E%E8%AE%BE%E8%AE%A1%E8%89%BA%E6%9C%AF%E5%AD%A6%E9%99%A2.html'
f = request.urlopen(url)
html = f.read().decode('utf-8')
# 使用正则表达式提取图片链接
pattern = r'<img.*?src="(.*?.jpg)".*?>'
img_urls = re.findall(pattern, html)
for t in range(len(img_urls)):
    img_urls[t] = 'file:///D:/学习资料/程序设计/python/爬虫/untitled' + img_urls[t]
# print(img_urls)
# 遍历图片链接，下载并保存图片
for i, img_url in enumerate(img_urls):
    try:
        # 发送HTTP请求，下载图片
        response = request.urlopen(img_url)
        img_data = response.read()
        # 提取图片文件名
        img_name = img_url.split('/')[-1]
        # 保存图片到本地
        with open(f'img_{i+1}_{img_name}', 'wb') as f:
            f.write(img_data)

        print(f'图片{i+1}保存成功')
    except Exception as e:
        print(f'图片{i+1}保存失败: {e}')
a = i

url = 'file:///D:/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/python/%E7%88%AC%E8%99%AB/untitled/%E8%AE%B2%E5%B8%88-%E6%95%B0%E5%AD%97%E5%AA%92%E4%BD%93%E4%B8%8E%E8%AE%BE%E8%AE%A1%E8%89%BA%E6%9C%AF%E5%AD%A6%E9%99%A2.htm'
f = request.urlopen(url)
html = f.read().decode('utf-8')
# 使用正则表达式提取图片链接
pattern = r'<img.*?src="(.*?.jpg)".*?>'
img_urls = re.findall(pattern, html)
for t in range(len(img_urls)):
    img_urls[t] = 'file:///D:/学习资料/程序设计/python/爬虫/untitled' + img_urls[t]
# print(img_urls)
# 遍历图片链接，下载并保存图片
for i, img_url in enumerate(img_urls):
    try:
        # 发送HTTP请求，下载图片
        response = request.urlopen(img_url)
        img_data = response.read()
        # 提取图片文件名
        img_name = img_url.split('/')[-1]
        # 保存图片到本地
        with open(f'img_{i+2+a}_{img_name}', 'wb') as f:
            f.write(img_data)

        print(f'图片{i+2+a}保存成功')
    except Exception as e:
        print(f'图片{i+2+a}保存失败: {e}')
a = i + a + 1

url = 'file:///D:/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/python/%E7%88%AC%E8%99%AB/untitled/%E6%95%99%E6%8E%88-%E6%95%B0%E5%AD%97%E5%AA%92%E4%BD%93%E4%B8%8E%E8%AE%BE%E8%AE%A1%E8%89%BA%E6%9C%AF%E5%AD%A6%E9%99%A2.htm'
f = request.urlopen(url)
html = f.read().decode('utf-8')
# 使用正则表达式提取图片链接
pattern = r'<img.*?src="(.*?.jpg)".*?>'
img_urls = re.findall(pattern, html)
for t in range(len(img_urls)):
    img_urls[t] = 'file:///D:/学习资料/程序设计/python/爬虫/untitled' + img_urls[t]
# print(img_urls)
# 遍历图片链接，下载并保存图片
for i, img_url in enumerate(img_urls):
    try:
        # 发送HTTP请求，下载图片
        response = request.urlopen(img_url)
        img_data = response.read()
        # 提取图片文件名
        img_name = img_url.split('/')[-1]
        # 保存图片到本地
        with open(f'img_{i+2+a}_{img_name}', 'wb') as f:
            f.write(img_data)

        print(f'图片{i+2+a}保存成功')
    except Exception as e:
        print(f'图片{i+2+a}保存失败: {e}')